﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace DoubleH.Utility.Net
{
   public class Http
    {
        /// <summary>
        /// 获取网页的HTML码
        /// </summary>
        /// <param name="url">链接地址</param>
        /// <param name="encoding">编码类型</param>
        /// <param name="timeout">定义超时(毫秒)如果没有响应,返回 string.empty</param>
        /// <returns></returns>
        public  string GetHtmlString(string url, Encoding encoding,int timeout=10000)
        {
            string htmlStr = "";
            if (!String.IsNullOrEmpty(url))
            {
                try
                {
                    WebRequest request = WebRequest.Create(url);            //实例化WebRequest对象
                    request.Timeout = timeout;
                    WebResponse response = request.GetResponse();           //创建WebResponse对象
                    Stream datastream = response.GetResponseStream();       //创建流对象
                    StreamReader reader = new StreamReader(datastream, encoding);
                    htmlStr = reader.ReadToEnd();                           //读取数据
                    reader.Close();
                    datastream.Close();
                    response.Close();
                }
                catch
                {
                    return string.Empty;
                }
            }
            return htmlStr.Trim();
        }
    }
}
